package GDoc::Job::Fetch::US::Exec::En::EIA::EPA;

use Moose;

use GDoc::Job;
use File::Temp;

extends 'GDoc::Job::Fetch';

sub setup { 
    my $self = shift;

    $self->_baseurl( 'http://www.eia.doe.gov/cneaf/electricity/epa/backissues.html' );
}

sub run { 
    my $self = shift;

    if ( $self->data->{link} ) { 
        $self->_fetch_pdf;
    } else { 
        $self->logger->info( "fetching base " . $self->_baseurl );

        my $mech = $self->_mech;
        $mech->get( $self->_baseurl );

        my @links = $mech->find_all_links( url_regex => qr{/0348\d{2,3}\.pdf$} );
        foreach my $link( @links ) { 
            $link->url =~ m{/0348(?<year>\d{2})(?<vol>\d)?\.pdf$};
            my $year = $+{year} > 90 ? $+{year} + 1900 : $+{year} + 2000;    # y2k dumbassery, sigh

            my $job = GDoc::Job->new( class => 'Fetch::US::Exec::En::EIA::EPA',
                                      queue => $self->fetch_queue,
                                      data  => { link    => $link->url,
                                                 year    => $year,
                                                 $+{vol} 
                                                 ? ( vol => $+{vol} )
                                                 : ( )
                                               }
                                    );

            $job->submit;
        }
    }
}


sub _fetch_pdf { 
    my $self = shift;
    my %data = %{ $self->data };

    my $ident = 'EIA-EPA-' . $data{year};
    $ident .= exists $data{vol} ? ( '-' . $data{vol} ) : '';

    my $desc = "Electric Power Annual, $data{year}" . 
      ( exists $data{vol}
        ? ", Vol. $data{vol}"
        : '' );

    my $filename = $ident . '.pdf';
    my $key = 'us/exec/en/eia/' . $filename;

    $self->logger->info( "Storing $data{link}  --> $key" );

    my $mech = $self->_mech;
    my $tmpf = File::Temp->new;
    $mech->get( $data{link}, ':content_file' => $tmpf->filename );

    $self->store_pdf( key       => $key,
                      datafile  => $tmpf,
                      filename  => $filename,
                      meta      => { description => $desc,
                                     identifier  => $ident
                                   }
                    );
}

1;
